using MediatR;
using WMS.Api.Application.Commands.Users;
using WMS.Common;
using WMS.Domain;
using WMS.Infrastructure;

namespace WMS.Api.Application.CommandHandlers.Users
{
    public class UpdateUserBalanceCommandHandler : IRequestHandler<UpdateUserBalanceCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<User> _userRepo;
        private readonly IBaseRepository<Record> _recordRepo;
        private readonly IMediator _mediator;

        public UpdateUserBalanceCommandHandler(
            IBaseRepository<User> userRepo, 
            IBaseRepository<Record> recordRepo,
            IMediator mediator)
        {
            _userRepo = userRepo;
            _recordRepo = recordRepo;
            _mediator = mediator;
        }

        public async Task<ApiResult<int>> Handle(UpdateUserBalanceCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>("修改用户金额");

            // 验证用户是否存在
            var user = (await _userRepo.GetAllAsync(o=>o.UserCode==request.UserCode)).FirstOrDefault();
            if (user == null)
            {
                result.isSuc = false;
                result.data = 0;
                result.msg = "用户不存在";
                result.code = StatusCodeEnum.Fail;
                return result;
            }

            // 计算新的余额
            int newBalance = user.Balance + request.PayAmount;
            
            // 更新用户余额
            user.Balance = newBalance;
            var updateResult = await _userRepo.UpdateAsync(user);

            if (updateResult > 0)
            {
                // 记录金额变动
                var record = new Record
                {
                    UserInfo = $"{user.UserCode}/{user.UserName}",
                    Type = 1,
                    PayType = request.PayType,
                    PayAmount = request.PayAmount,
                    PayDate = DateTime.Now,
                    Remark = request.Remark ?? string.Empty
                };

                await _recordRepo.AddNewAsync(record);

                result.isSuc = true;
                result.data = updateResult;
                result.msg = "金额修改成功";
                result.code = StatusCodeEnum.Ok;
            }
            else
            {
                result.isSuc = false;
                result.data = 0;
                result.msg = "金额修改失败";
                result.code = StatusCodeEnum.Fail;
            }

            return result;
        }
    }
} 